import 'package:flutter/cupertino.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmfutils/BaiduMap/bmfmap_utils.dart';
import 'package:flutter_bmfbase/BaiduMap/map/bmf_models.dart';
import 'package:flutter_bmflocation/bdmap_location_flutter_plugin.dart';
import 'package:flutter_bmflocation/flutter_baidu_location.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_android_option.dart';
import 'package:flutter_bmflocation/flutter_baidu_location_ios_option.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/api/api.dart';
import 'package:loxen/api/http_server/adderss.dart';
import 'package:loxen/dialog/toast.dart';
import 'package:loxen/mode/address_mode.dart';
import 'package:loxen/mode/base_mode.dart';
import 'package:loxen/mode/material/material_order_mode.dart';
import 'package:loxen/mode/operation_list_mode.dart' as OperationMode;
import 'package:loxen/utils/app_enum_util.dart';
import 'package:loxen/utils/map_url_util.dart';
import 'package:loxen/view/address/address_administration_widget.dart';
import 'package:loxen/view/address/service_list_widget.dart';
import 'package:loxen/view/material/material_order_receive/address_null_card.dart';
import 'package:loxen/view/material/material_order_receive/date_time_picker.dart';
import 'package:loxen/view/material/material_order_receive/material_list_card.dart';
import 'package:loxen/view/material/material_order_receive/operation_null_card.dart';
import 'package:loxen/view/material/material_order_receive/order_success_widget.dart';
import 'package:loxen/viewmode/base_view_model.dart';
import 'package:loxen/widget/fail_widget.dart';
import 'package:loxen/widget/loading_widget.dart';
import 'package:provider/provider.dart';
import 'package:loxen/utils/config.dart';
import 'package:loxen/view/material/material_order_receive/operation_center_card.dart' as Operation;
import 'package:loxen/view/material/material_order_receive/shipping_address_card.dart' as Shipping;
import 'package:loxen/widget/my_subassembly.dart';
import 'package:loxen/utils/string_res.dart';
import 'package:rxdart/rxdart.dart';

class _ViewModel extends BaseViewModel with AddressMixin {
  OrderType currentType = OrderType.DAO_DIAN_QU_YANG;
  BaiduLocation baiduLocation;
  String operationId;
  String year;
  String month;
  String day;
  String time;

  Address defaultAddr;
  OperationMode.Operation defaultOperation;
  List<OperationMode.Operation> listOperation;

  _ViewModel(this.currentType, this.operationId);

  void changeOperation(OperationMode.Operation operation) {
    defaultOperation = operation;
    notifyListeners();
  }

  void changeState(BaseState state) {
    mState = state;
    notifyListeners();
  }

  void setNull() {}

  void init() {
    Rx.zip3<Address, OperationMode.OperationList, dynamic, Future>(
        getDefaultAddress(),
        operations(operationId, baiduLocation.city),
        getOperationLists(operationId), (address, operations, event) async {
      if (address != null) {
        if (currentType == OrderType.TONG_CHENG_PEI_SONG) {
          List<List<BMFCoordinate>> locationList = [];
          List<String> locationId = [];
          if (event is List) {
            for (var data in event) {
              if (data is Map) {
                var locations = data['support_city_map'];
                if (locations is List) {
                  if (locations.length > 0) {
                    List<BMFCoordinate> listLocation = [];
                    for (var location in locations) {
                      if (location is Map) {
                        listLocation.add(BMFCoordinate(
                            double.parse(location['lat']), double.parse(location['lng'])));
                      }
                    }
                    locationList.add(listLocation);
                    locationId.add(data['id'].toString());
                  }
                }
              }
            }
          }
          address.isBeyond = true;
          for (int i = 0; i < locationList.length; i++) {
            var location = locationList[i];
            bool beyond = await BMFCalculateUtils.polygonContainsCoordinate(
                BMFCoordinate(address.lat, address.lng), location);
            if (beyond) {
              address.centerId = locationId[i];
              address.isBeyond = !beyond;
              defaultAddr = address;
              break;
            }
          }
        } else {
          defaultAddr = address;
        }
      }
      if (operations != null) {
        listOperation = operations.results;
      }
      if (address != null && operations != null) {
        return true;
      }
      return false;
    }).doOnListen(() {
      mState = BaseState.LOADING;
      notifyListeners();
    }).listen((event) async {
      if (listOperation != null && listOperation.length > 0) {
        double size = -1;
        for (var op in listOperation) {
          double my = await BMFCalculateUtils.getLocationDistance(
              BMFCoordinate(baiduLocation.latitude, baiduLocation.longitude),
              BMFCoordinate(double.parse(op.lat), double.parse(op.lng)));
          op.size = my;
          if (size == -1) {
            size = my;
            defaultOperation = op;
          } else {
            if (size > my) {
              size = my;
              defaultOperation = op;
            }
          }
        }
      }
      mState = BaseState.CONTENT;
      notifyListeners();
    }, onError: (error, stack) {
      mState = BaseState.FAIL;
      notifyListeners();
      print(error);
      print(stack);
    });
  }

  void setAddress(Address address) {
    defaultAddr = address;
    notifyListeners();
  }

  Stream<OperationMode.OperationList> operations(String id, String city) {
    return ApiService.operationList(id, city: city).flatMap((value) {
      return Stream.value(BaseMode<OperationMode.OperationList>(value.data));
    }).flatMap((value) => Stream.value(value?.data));
  }

  void putDaoDian(String ids, String remark, {Function() onSuccess, Function() onError}) {
    ApiService.putOrder(
      mode: '2',
      hsIds: ids,
      remark: remark,
      startTime: '$year-$month-$day ${time.split('-')[0]}',
      endTime: '$year-$month-$day ${time.split('-')[1]}',
      serviceId: defaultOperation.id.toString(),
    ).listen((event) {
      if (event.statusCode == 201) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call();
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call();
      print(stack);
    });
  }

  void putTongChengOrder(String ids, String remark, String serverId,
      {Function() onSuccess, Function() onError}) {
    ApiService.putOrder(
      addressId: defaultAddr.id.toString(),
      mode: '1',
      hsIds: ids,
      remark: remark,
      serviceId: serverId,
      startTime: '$year-$month-$day ${time.split('-')[0]}',
      endTime: '$year-$month-$day ${time.split('-')[1]}',
    ).listen((event) {
      if (event.statusCode == 201) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call();
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call();
      print(stack);
    });
  }

  void putKuaiDiOrder(String ids, String remark, {Function() onSuccess, Function() onError}) {
    ApiService.putOrder(addressId: defaultAddr.id.toString(), mode: '3', hsIds: ids, remark: remark)
        .listen((event) {
      if (event.statusCode == 201) {
        if (onSuccess != null) onSuccess.call();
      } else {
        if (onError != null) onError.call();
      }
    }, onError: (error, stack) {
      if (onError != null) onError.call();
      print(stack);
    });
  }

  void changeType(OrderType type) {
    if (currentType != OrderType.TONG_CHENG_PEI_SONG && type == OrderType.TONG_CHENG_PEI_SONG) {
      defaultAddr = null;
    }
    currentType = type;
    notifyListeners();
  }
}

class MaterialOrderReceiveWidget extends StatefulWidget {
  final OrderType orderType;
  final List<MaterialOrder> orderList;

  const MaterialOrderReceiveWidget({Key key, this.orderType, this.orderList}) : super(key: key);

  @override
  _MaterialOrderReceiveWidgetState createState() => _MaterialOrderReceiveWidgetState();
}

class _MaterialOrderReceiveWidgetState extends State<MaterialOrderReceiveWidget> {
  final ValueNotifier<String> time = ValueNotifier(null);
  final TextEditingController remarks = TextEditingController();
  final ScrollController controller = ScrollController();
  final FocusNode _myNode = new FocusNode();
  final LocationFlutterPlugin _locationPlugin = LocationFlutterPlugin();

  @override
  void dispose() {
    super.dispose();
    _locationPlugin.stopLocation();
  }

  void initLocation(BuildContext context, _ViewModel model) async {
    _locationPlugin.onResultCallback().listen((event) {
      BaiduLocation baiduLocation = BaiduLocation.fromMap(event);
      var code = event['errorCode'];
      if (code != null) {
        Toast.show('请确认开启定位权限，否则我无法获取到定位信息！', context);
        model.changeState(BaseState.FAIL);
        _locationPlugin.stopLocation();
        return;
      }
      if (baiduLocation.city != null) {
        _locationPlugin.stopLocation();
        model.baiduLocation = baiduLocation;
        model.init();
        return;
      }
    }, onError: (error) {
      print('定位失败');
    });
    bool data = await _locationPlugin.requestPermission();
    if (data) {
      _setLocOption();
      _locationPlugin.startLocation();
    } else {
      model.changeState(BaseState.FAIL);
      Toast.show('缺少权限，无法定位', context);
    }
  }

  void _setLocOption() {
    /// android 端设置定位参数
    BaiduLocationAndroidOption androidOption = BaiduLocationAndroidOption();
    androidOption.setCoorType("bd09ll"); // 设置返回的位置坐标系类型
    androidOption.setIsNeedAltitude(true); // 设置是否需要返回海拔高度信息
    androidOption.setIsNeedAddres(true); // 设置是否需要返回地址信息
    androidOption.setIsNeedLocationPoiList(true); // 设置是否需要返回周边poi信息
    androidOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    androidOption.setIsNeedLocationDescribe(true); // 设置是否需要返回位置描述
    androidOption.setOpenGps(true); // 设置是否需要使用gps
    androidOption.setLocationMode(LocationMode.Hight_Accuracy); // 设置定位模式
    androidOption.setScanspan(1000); // 设置发起定位请求时间间隔

    Map androidMap = androidOption.getMap();

    /// ios 端设置定位参数
    BaiduLocationIOSOption iosOption = BaiduLocationIOSOption();
    iosOption.setIsNeedNewVersionRgc(true); // 设置是否需要返回最新版本rgc信息
    iosOption.setBMKLocationCoordinateType("BMKLocationCoordinateTypeBMK09LL"); // 设置返回的位置坐标系类型
    iosOption.setActivityType("CLActivityTypeAutomotiveNavigation"); // 设置应用位置类型
    iosOption.setLocationTimeout(10); // 设置位置获取超时时间
    iosOption.setDesiredAccuracy("kCLLocationAccuracyBest"); // 设置预期精度参数
    iosOption.setReGeocodeTimeout(10); // 设置获取地址信息超时时间
    iosOption.setDistanceFilter(100); // 设置定位最小更新距离
    iosOption.setAllowsBackgroundLocationUpdates(true); // 是否允许后台定位
    iosOption.setPauseLocUpdateAutomatically(true); //  定位是否会被系统自动暂停

    Map iosMap = iosOption.getMap();

    _locationPlugin.prepareLoc(androidMap, iosMap);
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<_ViewModel>(
      create: (BuildContext context) {
        var mode = _ViewModel(widget.orderType, widget.orderList[0].brand.id.toString());
        initLocation(context, mode);
        return mode;
      },
      child: Scaffold(
        backgroundColor: Theme.of(context).backgroundColor,
        appBar: PreferredSize(
          preferredSize: Size(double.infinity, 95.h),
          child: Builder(
              builder: (context) => Container(
                    color: Theme.of(context).backgroundColor,
                    child: SafeArea(
                      child: Row(
                        children: <Widget>[
                          MySubassembly.getBackIcon(context,
                              color: Theme.of(context).textTheme.subtitle2.color),
                          Expanded(
                            child: Center(
                              child: Builder(
                                builder: (BuildContext context) {
                                  String text = context.select<_ViewModel, String>((value) {
                                    String data;
                                    switch (value.currentType) {
                                      case OrderType.KUAI_DI_JI_YANG:
                                        data = StringResources.kuai_di_ji_yang;
                                        break;
                                      case OrderType.TONG_CHENG_PEI_SONG:
                                        data = StringResources.tong_cheng_song_yang;
                                        break;
                                      case OrderType.DAO_DIAN_QU_YANG:
                                        data = StringResources.dao_dian_qu_yang;
                                        break;
                                    }
                                    return data;
                                  });
                                  return Text(
                                    text,
                                    style: TextStyle(
                                        fontSize: 32.sp,
                                        color: Theme.of(context).textTheme.subtitle2.color,
                                        fontWeight: FontWeight.w700),
                                  );
                                },
                              ),
                            ),
                          ),
                          MySubassembly.getSearchIcon(null, text: Constants.empty)
                        ],
                      ),
                    ),
                  )),
        ),
        body: Selector<_ViewModel, BaseState>(
            builder: (context, state, __) {
              Widget page;
              switch (state) {
                case BaseState.LOADING:
                  page = LoadingWidget();
                  break;
                case BaseState.EMPTY:
                  page = Constants.empty;
                  break;
                case BaseState.FAIL:
                  page = FailWidget(
                      onClick: () {
                        initLocation(context, context.read<_ViewModel>());
                      },
                      button: '重试');
                  break;
                case BaseState.CONTENT:
                  page = Container(
                    width: double.infinity,
                    child: SingleChildScrollView(
                      controller: controller,
                      child: Padding(
                        padding: EdgeInsets.only(left: 20.w, right: 20.w),
                        child: Column(
                          children: [
                            Divider(height: 30.h),
                            Builder(builder: (context) {
                              var type = context
                                  .select<_ViewModel, OrderType>((value) => value.currentType);
                              Widget page;
                              switch (type) {
                                case OrderType.TONG_CHENG_PEI_SONG:
                                  page = Selector<_ViewModel, Address>(
                                      builder: (_, address, ___) {
                                        if (address == null) {
                                          return AddressNullCard(onClick: () async {
                                            Address addr =
                                                await Navigator.of(context).push(MaterialPageRoute(
                                                    builder: (_) => AddressAdministrationWidget(
                                                          showDistance: true,
                                                          id: widget.orderList[0].brand.id
                                                              .toString(),
                                                        )));
                                            if (addr != null) {
                                              context.read<_ViewModel>().setAddress(addr);
                                            }
                                          });
                                        } else {
                                          return Shipping.ShippingAddressCard(
                                            onClick: () async {
                                              Address addr = await Navigator.of(context)
                                                  .push(MaterialPageRoute(
                                                      builder: (_) => AddressAdministrationWidget(
                                                            showDistance: true,
                                                            id: widget.orderList[0].brand.id
                                                                .toString(),
                                                          )));
                                              if (addr != null) {
                                                context.read<_ViewModel>().setAddress(addr);
                                              }
                                            },
                                            bean: Shipping.ItemBean(
                                              address.area.province,
                                              address.area.city,
                                              address.area.district,
                                              address.address,
                                              address.signer_name,
                                              address.signer_mobile,
                                            ),
                                          );
                                        }
                                      },
                                      selector: (_, value) => value.defaultAddr);
                                  break;
                                case OrderType.DAO_DIAN_QU_YANG:
                                  page = Selector<_ViewModel, OperationMode.Operation>(
                                      builder: (context, operation, _) {
                                        if (operation == null) {
                                          return OperationNullCard(
                                            onClick: () {
                                              var badu = context.read<_ViewModel>().baiduLocation;
                                              Navigator.of(context)
                                                  .push(MaterialPageRoute(
                                                      builder: (_) => ServiceListWidget(
                                                            city: badu.city,
                                                            operationId: context
                                                                .read<_ViewModel>()
                                                                .operationId,
                                                            myCoordinate: BMFCoordinate(
                                                                badu.latitude, badu.longitude),
                                                          )))
                                                  .then((value) {
                                                if (value != null) {
                                                  context.read<_ViewModel>().changeOperation(value);
                                                }
                                              });
                                            },
                                          );
                                        } else {
                                          return Operation.OperationCenterCard(
                                            onClick: () {
                                              var badu = context.read<_ViewModel>().baiduLocation;
                                              Navigator.of(context)
                                                  .push(MaterialPageRoute(
                                                      builder: (_) => ServiceListWidget(
                                                            city: badu.city,
                                                            operationId: context
                                                                .read<_ViewModel>()
                                                                .operationId,
                                                            myCoordinate: BMFCoordinate(
                                                                badu.latitude, badu.longitude),
                                                          )))
                                                  .then((value) {
                                                if (value != null) {
                                                  context.read<_ViewModel>().changeOperation(value);
                                                }
                                              });
                                            },
                                            goTo: () {
                                              MapUtil.gotoBaiduMap(
                                                  operation.lng, operation.lat, context);
                                              // var list = LocationUtil.bd09_To_Gcj02(
                                              //     double.parse(operation.lat),
                                              //     double.parse(operation.lng));
                                              // MapUtil.gotoTencentMap(list[1], list[0], context);
                                            },
                                            bean: Operation.ItemBean(
                                              operation.size < 1000
                                                  ? '${operation.size.toInt()}m'
                                                  : '${operation.size.toInt() / 1000}km',
                                              operation.name,
                                              operation.area.province,
                                              operation.area.city,
                                              operation.area.district,
                                              operation.address,
                                              operation.mobile,
                                            ),
                                          );
                                        }
                                      },
                                      selector: (_, value) => value.defaultOperation);
                                  break;
                                case OrderType.KUAI_DI_JI_YANG:
                                  page = Selector<_ViewModel, Address>(
                                      builder: (_, address, __) {
                                        if (address == null) {
                                          return AddressNullCard(onClick: () async {
                                            Address addr =
                                                await Navigator.of(context).push(MaterialPageRoute(
                                                    builder: (_) => AddressAdministrationWidget(
                                                          id: widget.orderList[0].brand.id
                                                              .toString(),
                                                        )));
                                            if (addr != null) {
                                              context.read<_ViewModel>().setAddress(addr);
                                            }
                                          });
                                        } else {
                                          return Shipping.ShippingAddressCard(
                                            onClick: () async {
                                              Address addr = await Navigator.of(context)
                                                  .push(MaterialPageRoute(
                                                      builder: (_) => AddressAdministrationWidget(
                                                            id: widget.orderList[0].brand.id
                                                                .toString(),
                                                          )));
                                              if (addr != null) {
                                                context.read<_ViewModel>().setAddress(addr);
                                              }
                                            },
                                            bean: Shipping.ItemBean(
                                              address.area.province,
                                              address.area.city,
                                              address.area.district,
                                              address.address,
                                              address.signer_name,
                                              address.signer_mobile,
                                            ),
                                          );
                                        }
                                      },
                                      selector: (_, value) => value.defaultAddr);
                                  break;
                              }
                              return page;
                            }),
                            Padding(
                              padding: EdgeInsets.only(top: 16.h),
                              child: Card(
                                elevation: 5,
                                child: Builder(
                                  builder: (BuildContext context) {
                                    return InkWell(
                                      onTap: () {
                                        openSelectOrderType(context);
                                      },
                                      child: Container(
                                        padding: EdgeInsets.fromLTRB(20.w, 30.h, 20.w, 30.h),
                                        width: 690.w,
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                '领样方式',
                                                style: TextStyle(
                                                    fontSize: 28.sp,
                                                    color: Color(0xff333333),
                                                    fontWeight: FontWeight.bold),
                                              ),
                                            ),
                                            Builder(
                                              builder: (BuildContext context) {
                                                var type = context.select<_ViewModel, OrderType>(
                                                    (value) => value.currentType);
                                                String str;
                                                switch (type) {
                                                  case OrderType.TONG_CHENG_PEI_SONG:
                                                    str = StringResources.tong_cheng_song_yang;
                                                    break;
                                                  case OrderType.DAO_DIAN_QU_YANG:
                                                    str = StringResources.dao_dian_qu_yang;
                                                    break;
                                                  case OrderType.KUAI_DI_JI_YANG:
                                                    str = StringResources.kuai_di_ji_yang;
                                                    break;
                                                }
                                                return Text(
                                                  str,
                                                  style: TextStyle(
                                                      fontSize: 28.sp, color: Color(0xff999999)),
                                                );
                                              },
                                            ),
                                            Image.asset(
                                              'images/mine_right.png',
                                              width: 30.w,
                                            ),
                                          ],
                                        ),
                                      ),
                                    );
                                  },
                                ),
                              ),
                            ),
                            Builder(builder: (context) {
                              var type = context
                                  .select<_ViewModel, OrderType>((value) => value.currentType);
                              if (type == OrderType.TONG_CHENG_PEI_SONG ||
                                  type == OrderType.DAO_DIAN_QU_YANG) {
                                return Padding(
                                  padding: EdgeInsets.only(top: 16.h),
                                  child: Card(
                                    elevation: 5,
                                    child: InkWell(
                                      onTap: () {
                                        openDatePicker(context);
                                      },
                                      child: Container(
                                        padding: EdgeInsets.only(left: 20.w, right: 20.w),
                                        height: 100.h,
                                        child: Row(
                                          children: [
                                            Expanded(
                                              child: Text(
                                                '送样时间',
                                                style: TextStyle(
                                                  fontSize: 28.sp,
                                                  color: Color(0xff333333),
                                                  fontWeight: FontWeight.bold,
                                                ),
                                              ),
                                            ),
                                            ValueListenableProvider.value(
                                              value: time,
                                              builder: (context, _) {
                                                String text = context.watch<String>();
                                                if (text != null) {
                                                  return Text(
                                                    text,
                                                    style: TextStyle(
                                                      fontSize: 28.sp,
                                                      color: Color(0xff666666),
                                                    ),
                                                  );
                                                } else {
                                                  return Text(
                                                    '请选择配送时间',
                                                    style: TextStyle(
                                                      fontSize: 28.sp,
                                                      color: Color(0xff666666),
                                                    ),
                                                  );
                                                }
                                              },
                                            ),
                                            Padding(
                                              padding: EdgeInsets.only(left: 20.w),
                                              child: Image.asset(
                                                'images/mine_right.png',
                                                width: 30.w,
                                              ),
                                            ),
                                          ],
                                        ),
                                      ),
                                    ),
                                  ),
                                );
                              } else {
                                return Constants.empty;
                              }
                            }),
                            materialList(),
                            Padding(
                              padding: EdgeInsets.only(top: 16.h, bottom: 120.h),
                              child: Card(
                                elevation: 5,
                                child: Container(
                                  width: double.infinity,
                                  child: Padding(
                                    padding: EdgeInsets.only(left: 20.w, right: 20.w),
                                    child: Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Padding(
                                          padding: EdgeInsets.only(top: 30.h),
                                          child: Text(
                                            '备注',
                                            style: TextStyle(
                                              fontSize: 28.sp,
                                              color: Color(0xFF333333),
                                              fontWeight: FontWeight.bold,
                                            ),
                                          ),
                                        ),
                                        Padding(
                                          padding: EdgeInsets.only(top: 30.h, bottom: 30.h),
                                          child: TextField(
                                            focusNode: _myNode,
                                            keyboardType: TextInputType.multiline,
                                            minLines: 1,
                                            maxLines: 10,
                                            controller: remarks,
                                            decoration: InputDecoration(
                                              hintText: '输入备注信息',
                                              border: InputBorder.none,
                                              isDense: true,
                                            ),
                                            style: TextStyle(
                                                color: Color(0xff333333), fontSize: 28.sp),
                                          ),
                                        )
                                      ],
                                    ),
                                  ),
                                ),
                              ),
                            ),
                            Container(
                              width: double.infinity,
                              height: 90.h,
                              margin: EdgeInsets.only(bottom: 120.h),
                              child: Builder(builder: (context) {
                                return FlatButton(
                                    onPressed: () {
                                      var model = context.read<_ViewModel>();
                                      if (model.defaultAddr == null) {
                                        Toast.show("请选择收货地址", context);
                                        return;
                                      }
                                      String ids = widget.orderList[0].products
                                          .map((e) => e.id)
                                          .toList()
                                          .join('_');
                                      switch (model.currentType) {
                                        case OrderType.TONG_CHENG_PEI_SONG:
                                          if (model.year == null) {
                                            Toast.show('请选择送样时间', context);
                                            return;
                                          }
                                          model.putTongChengOrder(ids, remarks.text.toString(),
                                              model.defaultAddr.centerId, onSuccess: () {
                                            Navigator.of(context)
                                                .push(MaterialPageRoute(
                                                    builder: (_) => OrderSuccessWidget()))
                                                .then((value) => Navigator.pop(context, true));
                                          }, onError: () {
                                            Toast.show('网络异常，下单失败', context);
                                          });
                                          break;
                                        case OrderType.DAO_DIAN_QU_YANG:
                                          if (model.year == null) {
                                            Toast.show('请选择送样时间', context);
                                            return;
                                          }
                                          if (model.defaultOperation == null) {
                                            Toast.show('请选择送服务中心', context);
                                            return;
                                          }
                                          model.putDaoDian(ids, remarks.text.toString(),
                                              onSuccess: () {
                                            Navigator.of(context)
                                                .push(MaterialPageRoute(
                                                    builder: (_) => OrderSuccessWidget()))
                                                .then((value) => Navigator.pop(context, true));
                                          }, onError: () {
                                            Toast.show('网络异常，下单失败', context);
                                          });
                                          break;
                                        case OrderType.KUAI_DI_JI_YANG:
                                          model.putKuaiDiOrder(ids, remarks.text.toString(),
                                              onSuccess: () {
                                            Navigator.of(context)
                                                .push(MaterialPageRoute(
                                                    builder: (_) => OrderSuccessWidget()))
                                                .then((value) => Navigator.pop(context, true));
                                          }, onError: () {
                                            Toast.show('网络异常，下单失败', context);
                                          });
                                          break;
                                      }
                                    },
                                    disabledColor: Colors.grey,
                                    color: Color(0xFF0CACCC),
                                    child: Text(
                                      '提交订单',
                                      style: TextStyle(
                                        fontSize: 32.sp,
                                        color: Colors.white,
                                      ),
                                    ));
                              }),
                            )
                          ],
                        ),
                      ),
                    ),
                  );
                  break;
              }
              return page;
            },
            selector: (_, value) => value.mState),
      ),
    );
  }

  Widget materialList() {
    return Column(
      children: widget.orderList.map((e) {
        return Padding(
          padding: EdgeInsets.only(top: 16.h),
          child: MaterialListCard(
            logo: e.brand.logo,
            list: e.products
                .map((e) => ItemBean(
                    image: e.cover, name: e.hsName, number: e.code, specifications: e.size))
                .toList(),
          ),
        );
      }).toList(),
    );
  }

  //时间选择器
  void openDatePicker(BuildContext context) async {
    var model = context.read<_ViewModel>();
    showModalBottomSheet(
        context: context,
        builder: (_) => DateTimePicker(
              day: 31,
              onSelect: (data) {
                String year = data[0];
                String month = data[1];
                String day = data[2];
                String time = data[3];
                model.year = year.substring(0, year.length - 1);
                model.month = month.substring(0, month.length - 1);
                model.day = day.substring(0, day.length - 1);
                model.time = time;
                this.time.value =
                    "${year.substring(0, year.length - 1)}-${month.substring(0, month.length - 1)}-${day.substring(0, day.length - 1)} $time";
              },
            ));
  }

  //打开选择 寄样方式
  void openSelectOrderType(BuildContext context) {
    showModalBottomSheet(
        context: context,
        builder: (mContext) {
          return Container(
            color: Theme.of(context).backgroundColor,
            height: 390.h,
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Padding(
                  padding: EdgeInsets.fromLTRB(30.w, 32.h, 30.w, 60.h),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          '领样方式',
                          style: TextStyle(
                            fontSize: 32.sp,
                            fontWeight: FontWeight.bold,
                            color: Color(0xff333333),
                          ),
                        ),
                      ),
                      IconButton(
                          icon: Icon(
                            Icons.close,
                            size: 30.w,
                          ),
                          onPressed: () {
                            Navigator.pop(mContext);
                          })
                    ],
                  ),
                ),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceAround,
                  children: [
                    iconText(
                      'images/tongcheng.png',
                      StringResources.tong_cheng_song_yang,
                      () {
                        context.read<_ViewModel>().changeType(OrderType.TONG_CHENG_PEI_SONG);
                        Navigator.pop(mContext);
                      },
                    ),
                    iconText(
                      'images/daodian.png',
                      StringResources.dao_dian_qu_yang,
                      () {
                        context.read<_ViewModel>().changeType(OrderType.DAO_DIAN_QU_YANG);
                        Navigator.pop(mContext);
                      },
                    ),
                    iconText(
                      'images/kuaidi.png',
                      StringResources.kuai_di_ji_yang,
                      () {
                        context.read<_ViewModel>().changeType(OrderType.KUAI_DI_JI_YANG);
                        Navigator.pop(mContext);
                      },
                    )
                  ],
                )
              ],
            ),
          );
        });
  }

  Widget iconText(String image, String text, Function() onClick) {
    return GestureDetector(
      onTap: onClick,
      child: Column(
        children: [
          Image.asset(
            image,
            width: 125.w,
            height: 125.w,
          ),
          Text(
            text,
            style: TextStyle(
              fontSize: 28.sp,
              color: Color(0xff333333),
            ),
          )
        ],
      ),
    );
  }
}
